package com.demarc.pesquisas.web.jsf;

import java.util.List;
import java.util.Map;

import javax.faces.component.UIComponent;

import org.primefaces.component.datatable.DataTable;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;

import com.demarc.pesquisas.infraestrutura.persistencia.ResultadoPaginado;
import com.demarc.pesquisas.infraestrutura.web.jsf.component.JsfComponentUtils;

@SuppressWarnings("unchecked")
public abstract class EntidadeLazyDataModel<T> extends LazyDataModel<T> {

	private static final long serialVersionUID = -8211378786013540425L;

	@Override
	public List<T> load(int first, int pageSize, String sortField,
			SortOrder sortOrder, Map<String, String> filters) {

		ResultadoPaginado<T> result = getResult(first, pageSize, sortField,
				sortOrder);
		setRowCount(result.getRowCount());
		resetTable();
		return result.getList();
	}

	@Override
	public Object getRowKey(T object) {
		return ((List<T>) getWrappedData()).indexOf(object);
	}

	@Override
	public void setRowIndex(int rowIndex) { // NOPMD
		if (getPageSize() == 0) {
			rowIndex = -1;
		}
		super.setRowIndex(rowIndex);
	}

	@Override
	public T getRowData(String rowKey) {
		int index = Integer.valueOf(rowKey);
		if (index >= 0) {
			return ((List<T>) getWrappedData()).get(index);
		}
		return null;
	}

	protected void resetTable() {
		UIComponent currentComponent = JsfComponentUtils.getCurrentComponent();
		if (currentComponent instanceof DataTable) {
			DataTable table = (DataTable) currentComponent;
			table.reset();
		}
	}

	public abstract ResultadoPaginado<T> getResult(int first, int pageSize,
			String sortField, SortOrder sortOrder);
}
